<template>
  <view class="app-container">
    <!-- 费用类别列表 -->
    <scroll-view scroll-y class="content">
      <view class="expense-list">
        <view v-for="(item, index) in expenseItems" :key="index" class="expense-item">
          <view class="expense-content">
            <view class="expense-title">{{ item.title }}</view>
            <view class="expense-description">{{ item.alt || item.content }}</view>
            <view v-if="item.supplement" class="expense-supplement">{{ item.supplement }}</view>
          </view>
          <view class="expense-actions">
            <view class="action-btn modify-btn" @click="modifyItem(index)">修改</view>
            <view v-if="!item.isOriginal" class="action-btn delete-btn" @click="deleteItem(index)">删除</view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部按钮组 -->
    <view class="bottom-buttons">
      <view class="bottom-btn add-btn" @click="showAddModal">
        <text class="btn-text">新增</text>
      </view>
      <view class="bottom-btn confirm-btn" @click="confirmAndReturn">
        <text class="btn-text">确定</text>
      </view>
    </view>

    <!-- 添加新项弹窗 -->
    <u-popup :show="showModal" mode="center" @close="cancelAdd">
      <view class="modal-container">
        <view class="modal-header">
          <text class="modal-title">{{ modalTitle }}</text>
        </view>
        
        <view class="modal-content">
          <view class="form-item">
            <text class="form-label">标题</text>
            <input 
              v-model="newItem.title" 
              :placeholder="currentItemIsOriginal ? '原始数据不可编辑' : '请输入标题'" 
              class="form-input"
              maxlength="50"
              :disabled="currentItemIsOriginal"
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">内容</text>
            <textarea 
              v-model="newItem.alt" 
              :placeholder="currentItemIsOriginal ? '原始数据不可编辑' : '请输入内容'" 
              class="form-textarea"
              maxlength="200"
              auto-height
              :disabled="currentItemIsOriginal"
            />
          </view>

          <view class="form-item" v-if="(userInfo.businessType == 2 && businessEntry == 'group_travel') || currentItemIsOriginal">
            <text class="form-label">补充说明</text>
            <textarea 
              v-model="newItem.supplement" 
              placeholder="请输入补充说明内容" 
              class="form-textarea"
              maxlength="150"
              auto-height
            />
          </view>
        </view>
        
        <view class="modal-footer">
          <view class="modal-btn cancel-btn" @click="cancelAdd">取消</view>
          <view class="modal-btn confirm-btn" @click="confirmAction">{{ confirmButtonText }}</view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { useProductStore } from '@/store/product';

export default {
  data() {
    return {
      productStore: null,
      type: '',
      pageTitle: '',
      toggleActive: true,
      showModal: false,
      modalTitle: '费用包含项目',
      confirmButtonText: '确定',
      isEditMode: false,
      editIndex: -1,
      currentItemIsOriginal: false, // 标记当前编辑的项是否为原始数据
      newItem: {
        title: '',
        alt: '',
        content: '',
        supplement: ''
      },
      expenseItems: [],
      userInfo: uni.getStorageSync('companyInfo'),
	  businessEntry:uni.getStorageSync('businessEntry')
    };
  },
  mounted() {
	  console.log('currentPage.options.type?')
    // 初始化productStore
    try {
      this.productStore = useProductStore();
    } catch (error) {
      console.error('初始化product store失败:', error);
      this.productStore = { 
        subPageData: { 
          expensesIncluded: [], 
          expensesExcluded: [], 
          otherExpenses: [] 
        }, 
        updateSubPageData: () => {} 
      };
    }

    // 获取页面参数
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
	console.log('currentPage.options.type',currentPage.options.type)
    this.type = currentPage.options.type || '';

    // 设置页面标题
    this.updatePageTitle();
    
    // 加载初始数据
    this.loadInitialData();
  },
  methods: {
    updatePageTitle() {
      if (this.type === 'included') this.pageTitle = '编辑费用包含';
      else if (this.type === 'excluded') this.pageTitle = '编辑费用不含';
      else if (this.type === 'other') this.pageTitle = '编辑另付费项目';
      else if (this.type === 'risk') this.pageTitle = '编辑风险提示';
      else if (this.type === 'guarantee') this.pageTitle = '编辑保障提示';
      else this.pageTitle = '编辑费用';
	  
	  
    },

    loadInitialData() {
      try {
        if (this.productStore && this.productStore.subPageData) {
          let items = [];
          
          if (this.type === 'included' && this.productStore.subPageData.expensesIncluded) {
            items = [...this.productStore.subPageData.expensesIncluded];
          } else if (this.type === 'excluded' && this.productStore.subPageData.expensesExcluded) {
            items = [...this.productStore.subPageData.expensesExcluded];
          } else if (this.type === 'other' && this.productStore.subPageData.otherExpenses) {
            items = [...this.productStore.subPageData.otherExpenses];
          } else if (this.type === 'risk' && this.productStore.subPageData.riskPrompt) {
            // 风险提示现在是数组类型，直接使用
            if (Array.isArray(this.productStore.subPageData.riskPrompt)) {
              items = [...this.productStore.subPageData.riskPrompt];
            } else {
              // 兼容旧的字符串格式
              items = this.productStore.subPageData.riskPrompt ? [{
                title: '风险提示',
                alt: this.productStore.subPageData.riskPrompt,
                id: 1
              }] : [];
            }
          } else if (this.type === 'guarantee' && this.productStore.subPageData.guaranteePrompt) {
            // 保障提示现在是数组类型，直接使用
            if (Array.isArray(this.productStore.subPageData.guaranteePrompt)) {
              items = [...this.productStore.subPageData.guaranteePrompt];
            } else {
              // 兼容旧的字符串格式
              items = this.productStore.subPageData.guaranteePrompt ? [{
                title: '保障提示',
                alt: this.productStore.subPageData.guaranteePrompt,
                id: 1
              }] : [];
            }
          }
          
          // 如果没有数据，保持为空数组，不初始化默认数据
          if (items.length === 0) {
            this.expenseItems = [];
          } else {
            // 为每个加载的数据项添加 isOriginal 标记
            // 如果数据项已经有 isOriginal 标记，则保留它；否则设置为 true（表示原始数据）
            this.expenseItems = items.map(item => ({
              ...item,
              alt: item?.alt || item?.content || '',
              content: item?.content || item?.alt || '',
              supplement: item?.supplement || '',
              isOriginal: item.hasOwnProperty('isOriginal') ? item.isOriginal : true
            }));
          }
        } else {
          // 没有产品数据时，也保持为空数组
          this.expenseItems = [];
        }
      } catch (e) {
        console.error('加载初始数据失败:', e);
        // 出错时也保持为空数组
        this.expenseItems = [];
      }
    },


    initializeDefaultItems() {
      // 根据类型初始化默认的费用项目
      if (this.type === 'included') {
        this.expenseItems = [
          {
            title: '交通',
            alt: '全程交通 旅游巴士 包车往返\n目的地 - 出发地交通 郑州二七~新乡辉县 G高铁',
            content: '全程交通 旅游巴士 包车往返\n目的地 - 出发地交通 郑州二七~新乡辉县 G高铁',
            id: 1
          },
          {
            title: '用餐',
            alt: '8次 活动期间的餐费',
            content: '8次 活动期间的餐费',
            id: 2
          },
          {
            title: '门票',
            alt: '行程所列景点/场馆首到大门票',
            content: '行程所列景点/场馆首到大门票',
            id: 3
          },
          {
            title: '人员',
            alt: '行程中涉及的工作人员及服务费用',
            content: '行程中涉及的工作人员及服务费用',
            id: 4
          },
          {
            title: '策划设计',
            alt: '行程中涉及的策划设计的服务费用',
            content: '行程中涉及的策划设计的服务费用',
            id: 5
          }
        ];
      } else if (this.type === 'excluded') {
        this.expenseItems = [
          {
            title: '个人消费',
            alt: '个人购物、纪念品等消费',
            content: '个人购物、纪念品等消费',
            id: 1
          },
          {
            title: '保险费用',
            alt: '个人旅游意外保险',
            content: '个人旅游意外保险',
            id: 2
          }
        ];
      } else if (this.type === 'other') {
        this.expenseItems = [
          {
            title: '额外活动',
            alt: '自费参加的额外活动项目',
            content: '自费参加的额外活动项目',
            id: 1
          }
        ];
      } else if (this.type === 'risk') {
        this.expenseItems = [
          {
            title: '风险提示',
            alt: '请在此输入风险提示内容...',
            content: '请在此输入风险提示内容...',
            id: 1
          }
        ];
      } else if (this.type === 'guarantee') {
        this.expenseItems = [
          {
            title: '保障提示',
            alt: '请在此输入保障提示内容...',
            content: '请在此输入保障提示内容...',
            id: 1
          }
        ];
      }
    },

    modifyItem(index) {
      const item = this.expenseItems[index];
      this.isEditMode = true;
      this.editIndex = index;
      // 检查是否为原始数据
      this.currentItemIsOriginal = !!item.isOriginal;
      this.modalTitle = '费用包含项目';
      this.confirmButtonText = '保存';
      this.newItem = {
        title: item.title,
        alt: item.alt,
        content: item.content || item.alt,
        supplement: item.supplement || ''
      };
      this.showModal = true;
    },

    deleteItem(index) {
      // 检查是否为原始数据，如果是则不允许删除
      if (this.expenseItems[index].isOriginal) {
        uni.showToast({ title: '原始数据不可删除', icon: 'none' });
        return;
      }
      
      if (this.expenseItems.length <= 1) {
        uni.showToast({ title: '至少保留一项', icon: 'none' });
        return;
      }
      
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个费用项目吗？',
        success: (res) => {
          if (res.confirm) {
            this.expenseItems.splice(index, 1);
            this.saveData();
          }
        }
      });
    },

    // 显示添加弹窗
    showAddModal() {
      this.isEditMode = false;
      this.editIndex = -1;
      this.currentItemIsOriginal = false; // 新增时标记为非原始数据
      this.modalTitle = '费用包含项目';
      this.confirmButtonText = '确定';
      this.newItem = {
        title: '',
        alt: '',
        content: '',
        supplement: ''
      };
      this.showModal = true;
    },

    // 取消操作
    cancelAdd() {
      this.showModal = false;
      this.isEditMode = false;
      this.editIndex = -1;
      this.currentItemIsOriginal = false;
      this.newItem = {
        title: '',
        alt: '',
        content: '',
        supplement: ''
      };
    },

    // 统一确认操作
    confirmAction() {
      if (!this.newItem.title.trim()) {
        uni.showToast({ title: '请输入标题', icon: 'none' });
        return;
      }
      if (!this.newItem.alt.trim()) {
        uni.showToast({ title: '请输入内容', icon: 'none' });
        return;
      }

      if (this.isEditMode) {
        // 编辑模式：更新现有项目
        const title = this.newItem.title.trim();
        const content = this.newItem.alt.trim();
        this.newItem.content = content;
        this.expenseItems[this.editIndex].title = title;
        this.expenseItems[this.editIndex].alt = content;
        this.expenseItems[this.editIndex].content = content;
        this.expenseItems[this.editIndex].supplement = this.newItem.supplement.trim();
        // 取消 isOriginal 标记，表示已经被修改过
        this.expenseItems[this.editIndex].isOriginal = false;
        uni.showToast({ title: '修改成功', icon: 'success' });
      } else {
        // 添加模式：创建新项目
        const content = this.newItem.alt.trim();
        const newItem = {
          title: this.newItem.title.trim(),
          alt: content,
          content,
          supplement: this.newItem.supplement.trim(),
          id: Date.now(),
          isOriginal: false // 新添加的数据标记为非原始数据
        };
        this.expenseItems.push(newItem);
        uni.showToast({ title: '添加成功', icon: 'success' });
      }
      
      this.saveData();
      this.showModal = false;
      this.isEditMode = false;
      this.editIndex = -1;
      this.newItem = {
        title: '',
        alt: '',
        content: '',
        supplement: ''
      };
    },

    saveData() {
      try {
        console.log('💾 开始保存数据，类型:', this.type);
        console.log('💾 当前expenseItems:', JSON.stringify(this.expenseItems, null, 2));
        
        if (this.productStore) {
          // 确保subPageData存在
          if (!this.productStore.subPageData) {
            this.productStore.subPageData = {};
          }
          
          if (this.type === 'included') {
            this.productStore.subPageData.expensesIncluded = [...this.expenseItems];
            console.log('💾 已保存expensesIncluded:', JSON.stringify(this.productStore.subPageData.expensesIncluded, null, 2));
          } else if (this.type === 'excluded') {
            this.productStore.subPageData.expensesExcluded = [...this.expenseItems];
            console.log('💾 已保存expensesExcluded:', JSON.stringify(this.productStore.subPageData.expensesExcluded, null, 2));
          } else if (this.type === 'other') {
            this.productStore.subPageData.otherExpenses = [...this.expenseItems];
            console.log('💾 已保存otherExpenses:', JSON.stringify(this.productStore.subPageData.otherExpenses, null, 2));
          } else if (this.type === 'risk') {
            // 风险提示保存为数组类型，与费用包含/不含保持一致
            this.productStore.subPageData.riskPrompt = [...this.expenseItems];
            console.log('💾 已保存riskPrompt:', JSON.stringify(this.productStore.subPageData.riskPrompt, null, 2));
          } else if (this.type === 'guarantee') {
            // 保障提示保存为数组类型，与费用包含/不含保持一致
            this.productStore.subPageData.guaranteePrompt = [...this.expenseItems];
            console.log('💾 已保存guaranteePrompt:', JSON.stringify(this.productStore.subPageData.guaranteePrompt, null, 2));
          }
          
          console.log('💾 保存完成，productStore.subPageData:', JSON.stringify(this.productStore.subPageData, null, 2));
        } else {
          console.error('❌ productStore 不存在');
        }
      } catch (e) {
        console.error('❌ 保存数据失败:', e);
      }
    },

    // 确定并返回
    confirmAndReturn() {
      console.log('✅ 点击确定按钮，准备返回父页面');
      this.saveData();
      console.log('✅ 数据保存完成，准备返回');
      uni.navigateBack();
    },

    goBack() {
      this.saveData();
      uni.navigateBack();
    }
  }
};
</script>

<style scoped>
.app-container {
  display: flex;
  flex-direction: column;
  /* height: 100vh; */
  padding: 0rpx 20rpx;
  background-color: #fff;
}

/* 顶部导航栏样式 */
.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #f0f0f0;
  height: 88rpx;
  box-sizing: border-box;
}

.nav-left {
  flex: 1;
}

.back-btn {
  display: flex;
  align-items: center;
  padding: 8rpx 16rpx;
  background-color: #f8f8f8;
  border-radius: 20rpx;
  width: fit-content;
}

.back-arrow {
  font-size: 32rpx;
  color: #666;
  margin-right: 8rpx;
}

.back-text {
  font-size: 28rpx;
  color: #666;
}

.nav-title {
  flex: 2;
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.nav-right {
  flex: 1;
  display: flex;
  justify-content: flex-end;
}

/* 开关样式 */
.toggle-switch {
  width: 60rpx;
  height: 32rpx;
  background-color: #e0e0e0;
  border-radius: 16rpx;
  position: relative;
  transition: background-color 0.3s ease;
}

.toggle-switch.active {
  background-color: #007aff;
}

.toggle-thumb {
  width: 28rpx;
  height: 28rpx;
  background-color: #fff;
  border-radius: 50%;
  position: absolute;
  top: 2rpx;
  left: 2rpx;
  transition: transform 0.3s ease;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
}

.toggle-switch.active .toggle-thumb {
  transform: translateX(28rpx);
}

/* 内容区域 */
.content {
  flex: 1;
  /* padding: 0 30rpx; */
  max-height: calc(100vh - 200rpx);
  overflow: hidden;
}

.expense-list {
  padding-top: 20rpx;
  padding-bottom: 120rpx;
}

/* 费用项目样式 */
.expense-item {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  min-height: 80rpx;
}

.expense-item:last-child {
  border-bottom: none;
}

.expense-content {
  flex: 1;
  margin-right: 20rpx;
  max-width: calc(100% - 200rpx);
}

.expense-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.expense-description {
  font-size: 26rpx;
  color: #666;
  line-height: 1.4;
  white-space: pre-line;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.expense-supplement {
  font-size: 24rpx;
  color: #999;
  line-height: 1.3;
  white-space: pre-line;
  word-wrap: break-word;
  overflow-wrap: break-word;
  margin-top: 8rpx;
  padding: 8rpx 12rpx;
  background-color: #f8f9fa;
  border-radius: 6rpx;
}

/* 操作按钮样式 */
.expense-actions {
  display: flex;
  /* gap: 10rpx; */
  flex-shrink: 0;
  /* width: 200rpx; */
  align-items: center;
  justify-content: space-around;
  
}

.action-btn {
  /* padding: 20rpx 8rpx; */
  width:72rpx;
  height:72rpx;
  line-height: 72rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  font-weight: 500;
  text-align: center;
  flex: 1;
  white-space: nowrap;
  margin-right: 20rpx;
}

.modify-btn {
  background-color: rgba(0, 129, 255, 0.1);
  border: none;
  color: #007aff;
  border: 1rpx solid;
}

.delete-btn {
  background-color: #fff;
  border: none;
  color: #ff6600;
  border:1rpx solid;
}

/* 底部按钮组 */
.bottom-buttons {
  position: fixed;
  bottom: 30rpx;
  left: 20rpx;
  right: 20rpx;
  display: flex;
  gap: 20rpx;
  z-index: 100;
}

.bottom-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
}

.add-btn {
  background-color: #007aff;
}

.confirm-btn {
  background-color: #00c389;
}

.btn-text {
  font-size: 32rpx;
  color: #fff;
  font-weight: 500;
}

/* 弹窗样式 */
.modal-container {
  width: 600rpx;
  padding: 40rpx;
  background-color: #fff;
  border-radius: 20rpx;
  box-sizing: border-box;
}

.modal-header {
  text-align: center;
  margin-bottom: 30rpx;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.modal-content {
  margin-bottom: 40rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 12rpx;
  font-weight: 500;
}

.form-input {
  width: 100%;
  height: 80rpx;
  padding: 0 20rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  font-size: 28rpx;
  line-height: 80rpx;
  box-sizing: border-box;
  background-color: #fff;
}

.form-input:focus {
  border-color: #007aff;
}

/* 禁用状态的输入框样式 */
.form-input[disabled],
.form-input:disabled {
  background-color: #e8e8e8 !important;
  color: #888 !important;
  border-color: #d0d0d0 !important;
  cursor: not-allowed;
  user-select: none;
}

.form-textarea {
  width: 100%;
  min-height: 120rpx;
  padding: 20rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background-color: #fff;
  resize: none;
}

.form-textarea:focus {
  border-color: #007aff;
}

/* 禁用状态的文本域样式 */
.form-textarea[disabled],
.form-textarea:disabled {
  background-color: #e8e8e8 !important;
  color: #888 !important;
  border-color: #d0d0d0 !important;
  cursor: not-allowed;
  user-select: none;
}

.modal-footer {
  display: flex;
  justify-content: space-between;
  gap: 20rpx;
}

.modal-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 12rpx;
  font-size: 28rpx;
  font-weight: 500;
}

.cancel-btn {
  background-color: #f8f8f8;
  color: #666;
  border: 2rpx solid #e0e0e0;
}

.confirm-btn {
  background-color: #007aff;
  color: #fff;
  border: 2rpx solid #007aff;
}
</style>